<?php
!defined('DEBUG') AND exit('Forbidden');
$threadext_cfg = null;
if(!function_exists('get_plugin_config')){
    $conffile = dirname(__FILE__).DIRECTORY_SEPARATOR.'conf.json';
    if (is_file($conffile)) {
        $threadext_cfg = xn_json_decode(file_get_contents($conffile));
    }
}
else
{
    $threadext_cfg = &get_plugin_config($dir);
}


if (!function_exists('FixSqlFieldComment')) {
    /**
     * 对SQL语句中的字段注释进行转换
     * @param string|string[] $sql sql语句
     * @param $dbtype 数据库类型
     * @return string|string[]|null
     */
    function &FixSqlFieldComment($sql, $dbtype)
    {
        if (!empty($sql)) {
            $reg = '';
            $rep = '';
            switch ($dbtype){
                case 'sqlite':
                case 'pdo_sqlite':
                    $reg = '#\bCOMMENT\s+([\'"])(.*?)\1(?<!\\\1)#gisu';
                    $rep = '/*$2*/';
                    break;
                case 'mysql':
                case 'mysqli':
                case 'pdo_mysql':
                    $reg = '#\s+\-\-(.*)$#giu';
                    $rep = ' COMMENT \'$1\'';
                    break;
                default:
                    break;
            }
            if(!empty($reg)){
                $count = 0;
                $sql = preg_replace($reg, $rep, $sql, -1, $count);
            }
        }
        return $sql;
    }
}

$is_duplicate_run = false;
$agreement = param('agreement');
if (($agreement !== 'agree' && $agreement !== 'yes') || $method != 'POST') {
    $testurl = '/plugin-install-'.$dir.'.htm';
    if($method == 'GET' && stripos($_SERVER['HTTP_REFERER'],$testurl) > 0){
        $is_duplicate_run = true;
        plugin_lock_end();
        header("location:".dirname($_SERVER['PHP_SELF']).'/plugin.htm');
    }
    else {
        if (isset($plugins[$dir])) {
            $plugins[$dir]['installed'] = 0;
            $plugins[$dir]['enable'] = 0;
            // 写入配置文件
            file_replace_var(APP_PATH . "plugin/$dir/conf.json", array('installed' => $plugins[$dir]['installed'], 'enable' => $plugins[$dir]['enable']), TRUE);
            $header['title'] = '同意用户协议[Agree to user agreement],' . ',' . $header['title'];
            include _include(APP_PATH . 'plugin/' . $dir . '/htm/agreement.htm');
            $_SERVER['HTTP_REFERER'] = dirname($_SERVER['PHP_SELF']).'/plugin.htm';
        }
        plugin_lock_end();
        exit(0);
    }
}
if($is_duplicate_run == false) {
    $threadext_tb = 'threadext';
    $postflag_tb = 'postflag';
    $label_tb = 'label';
    $labelog_tb = 'labelog';

    if (!empty($threadext_cfg['ThreadextTable'])) $threadext_tb = $threadext_cfg['ThreadextTable'];
    if (!empty($threadext_cfg['Label']['LabelTable'])) $label_tb = $threadext_cfg['Label']['LabelTable'];
    if (!empty($threadext_cfg['Label']['LabellogTable'])) $labelog_tb = $threadext_cfg['Label']['LabellogTable'];
    if (!empty($threadext_cfg['PostFlag']['table'])) $postflag_tb = $threadext_cfg['PostFlag']['table'];

    if (empty($tablepre)) $tablepre = $db->tablepre;

    $sql = "CREATE TABLE IF NOT EXISTS `{$tablepre}{$threadext_tb}` (
    `id` int(11) unsigned NULL AUTO_INCREMENT,
	`tid` int(11) unsigned NOT NULL,
	`keywords` varchar(250) NULL DEFAULT '' COMMENT 'META关键词',			
	`metadesc` varchar(350) NULL DEFAULT '' COMMENT 'META说明',
	`firstimg` varchar(200) NULL DEFAULT '' COMMENT '标题图片',
	`expired` int(11) unsigned NULL DEFAULT 0 COMMENT '过期时间,会定期清理,0为不过期',
	`source` varchar(64) NULL DEFAULT '' COMMENT '来源',
	`sourceurl` varchar(1024) NULL DEFAULT '' COMMENT '来源链接',
	`editornote` varchar(1024) NULL DEFAULT '' COMMENT '编者按',
	`reviseerr` varchar(2048) NULL DEFAULT '' COMMENT '修订意见与纠错',
	`aflags` int(11) NULL DEFAULT 0 COMMENT '附加标志位',
	`relatedlinks` varchar(4096) NULL DEFAULT '' COMMENT '相关链接',
    `relatedfids` varchar(60) NULL DEFAULT '' COMMENT '关联板块列表',
    `relatedupdtime` int(11) NULL DEFAULT 0 COMMENT '更新关联时间',
    `viwetemplate` VARCHAR(255) NULL DEFAULT '' COMMENT '展示模板',
	PRIMARY KEY (tid),
	KEY (`id`),
	KEY (`expired`),
	KEY (aflags),
	KEY (source),
	KEY `relatedupdatetime` (`relatedupdtime`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci COMMENT = '主题扩展表';
CREATE TABLE IF NOT EXISTS `{$tablepre}{$postflag_tb}` (
    `id` INT NULL AUTO_INCREMENT COMMENT '标签记录ID',
	`pid` int(11) UNSIGNED NOT NULL COMMENT '贴子ID',
	`tid` int(11) UNSIGNED NULL DEFAULT 0 COMMENT '主题ID',
	`fid` int(11) UNSIGNED NULL DEFAULT 0 COMMENT '版块ID',
	`isfirst` TINYINT(4) NULL DEFAULT 0 COMMENT '是否为主贴',
	`hide` TINYINT(4) NULL DEFAULT 0 COMMENT '隐藏',
	PRIMARY KEY (`pid`),
	KEY (`id`),
	KEY (`fid`),
	KEY (`tid`),
	KEY (`isfirst`),
	KEY `flaghide` (`hide`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci COMMENT = '帖子标志表';
CREATE TABLE IF NOT EXISTS `{$tablepre}{$label_tb}` (
    `id` INT NOT NULL AUTO_INCREMENT COMMENT '标签ID' ,
    `name` VARCHAR(32) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT '标签名' ,
    `cate` INT NULL DEFAULT '0' COMMENT '分类值' ,
    `counter` INT NULL DEFAULT '0' COMMENT '计数' ,
    `subtable` INT NULL DEFAULT '0' COMMENT '分表号',
    PRIMARY KEY (`id`),
    KEY `labelcate` (`cate`),
    KEY `usecount` (`counter`),
    UNIQUE KEY `labelname` (`name`),
    KEY `Sub-table` (`subtable`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci COMMENT = '通用标签表';
CREATE TABLE IF NOT EXISTS `{$tablepre}{$labelog_tb}0` (
`id` INT NOT NULL AUTO_INCREMENT COMMENT '标签记录ID' ,
`lid` INT NOT NULL COMMENT '标签ID' ,
`dist` INT NOT NULL COMMENT '目标代码' ,
`distid` INT NOT NULL COMMENT '目标ID' ,
`distclass` INT NULL DEFAULT '0' COMMENT '目标分类' ,
`disabled` TINYINT NULL DEFAULT '0' COMMENT '禁用',
`rank` INT NULL DEFAULT '0' COMMENT '排序系数' ,
`atime` INT NULL DEFAULT '0' COMMENT '记录时间' ,
`ztime` INT NULL DEFAULT '0' COMMENT '有效时间' ,
`info` VARCHAR(512) NULL DEFAULT '' COMMENT '标记说明' ,
`sign` INT NULL DEFAULT '0' COMMENT '标志位值' ,
`vint` INT NULL DEFAULT '0' COMMENT 'INT附值' ,
`vdouble` DOUBLE NULL DEFAULT '0' COMMENT 'DOUBLE附值' ,
`vstr` VARCHAR(50) NULL DEFAULT '' COMMENT '字符串附值' ,
PRIMARY KEY (`id`), INDEX `labelrank` (`rank`),
UNIQUE KEY `labelrow` (`lid`, `dist`, `distid`,`sign`) USING BTREE,
KEY `labeltime` (`atime`,`ztime`,`disabled`),
KEY `labelatint` (`vint`),
KEY `labelatstr` (`vstr`),
KEY `distclass` (`distclass`)
) ENGINE = MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci COMMENT = '标签记录表0';";
    if ($conf['db']['type'] == 'sqlite' || $conf['db']['type'] == 'pdo_sqlite') $sql = &FixSqlFieldComment($sql, $conf['db']['type']);
    $r = db_exec($sql);
if($r !== false) {
    $sql = "ALTER TABLE `{$tablepre}thread` ADD `trank` INT NULL DEFAULT '0' COMMENT '排序指数', ADD INDEX `trank` (`trank`);
ALTER TABLE `{$tablepre}post` ADD `prank` INT NULL DEFAULT '0' COMMENT '排序指数', ADD INDEX `prank` (`prank`);";
    if ($conf['db']['type'] == 'sqlite' || $conf['db']['type'] == 'pdo_sqlite') $sql = &FixSqlFieldComment($sql, $conf['db']['type']);
    $r2 = db_exec($sql);
}
}
else{
    $_SERVER['HTTP_REFERER'] = dirname($_SERVER['PHP_SELF']).'/plugin.htm';
    plugin_lock_end();
}

 